<template>
  <div class="home scroll-theme">
    <div class="content">
      <sidebar-wrap></sidebar-wrap>
      <div class="conArea">
        <nav-wrap></nav-wrap>
        <div class="create-charts">
          <div class="control-pane scroll-theme">
            <el-row style="height:100%;">
              <el-col :span="17" class="canvasdraw">
                <div class="show-pane">
                  <drawcharts ref="drawChart" :dropData="dropData"></drawcharts>
                </div>
                <div class="save-btn">
                  <el-button
                    size="small"
                    icon="el-icon-box"
                    type="primary"
                    @click="saveCharts"
                    >保存</el-button
                  >
                  <el-button
                    size="small"
                    icon="el-icon-switch-button"
                    type="primary"
                    @click="quit"
                    >退出</el-button
                  >
                  <el-button
                    id="download"
                    size="small"
                    icon="el-icon-download"
                    type="primary"
                    @click="loadImg"
                    >下载缩略图</el-button
                  >
                  <el-button
                    id="downloadData"
                    size="small"
                    icon="el-icon-download"
                    type="primary"
                    @click="downloadData"
                    >下载数据</el-button
                  >
                </div>
              </el-col>
              <el-col
                class="scroll-theme"
                :span="7"
                style="height:100%;float:right;overflow:auto;"
              >
                <el-collapse v-model="activeName" accordion>
                  <el-collapse-item
                    title="图表选择"
                    name="1"
                    style="background-color: #f9f9f9;"
                  >
                    <div class="searchCharts" style="margin:15px 0;">
                      <el-input
                        size="small"
                        placeholder="请输入图表名称"
                        v-model="keywords"
                        @input="handleSearch"
                        prefix-icon="el-icon-search"
                        class="input-with-select"
                      >
                      </el-input>
                    </div>
                    <div class="charts-select-con">
                      <el-row>
                        <el-col :span="6">
                          <el-menu
                            default-active="0"
                            class="el-menu-vertical-demo"
                          >
                            <el-menu-item
                              v-for="(item, i) in chartsType"
                              :key="item"
                              :index="i + ''"
                              @click="handleChartsType(item)"
                            >
                              <span slot="title">{{ item }}</span>
                            </el-menu-item>
                          </el-menu>
                        </el-col>
                        <el-col :span="18">
                          <chartsType
                            :chartsName="chartsName"
                            :mychartsDom="mychartsDom"
                            @renderData="renderData"
                          >
                          </chartsType>
                        </el-col>
                      </el-row>
                    </div>
                  </el-collapse-item>
                  <el-collapse-item
                    class="chartAttr"
                    title="图表属性及数据"
                    name="2"
                  >
                    <chartsCondition
                      @clearHtml="clearHtml"
                      @rePaint="rePaint"
                      @renderData="renderData"
                      ref="chartsCondition"
                      :activeName="activeName"
                    >
                    </chartsCondition>
                  </el-collapse-item>
                  <el-collapse-item title="样式主题" name="3">
                    <el-form
                      class="themeStyle"
                      style="margin:15px;"
                      size="small"
                    >
                      <el-form-item>
                        <p>主题</p>
                        <div class="themeDiv">
                          <div
                            v-for="(item1, key) in themeColor"
                            :key="key"
                            :ref="key"
                            @click="setTheme(key)"
                          >
                            <div
                              :class="[
                                'default-theme',
                                { 'theme-active': chartsConData.theme === key }
                              ]"
                              v-if="key.includes('default')"
                            >
                              <span
                                v-for="(item, index) in item1"
                                :key="index"
                                :style="{ 'background-color': item }"
                              ></span>
                            </div>
                          </div>
                        </div>
                      </el-form-item>
                      <el-form-item>
                        <p>自定义主题</p>
                        <div class="themeDiv">
                          <div
                            v-for="(item1, key) in themeColor"
                            :key="key"
                            ref="key"
                            @click="setTheme(key)"
                          >
                            <div
                              class="define-theme1"
                              :class="{
                                'theme-active': chartsConData.theme === key
                              }"
                              v-if="key.includes('define')"
                            >
                              <el-color-picker
                                v-for="(item, index) in item1"
                                :key="index"
                                v-model="themeColor[key][index]"
                                show-alpha
                                :predefine="predefineColors"
                                @change="
                                  handlePicker(themeColor[key][index], index)
                                "
                              >
                              </el-color-picker>
                            </div>
                          </div>
                        </div>
                      </el-form-item>
                    </el-form>
                  </el-collapse-item>
                </el-collapse>
              </el-col>
            </el-row>
          </div>
          <confirmDialog
            @rePaint="rePaint"
            :show.sync="showCon"
          ></confirmDialog>
          <!-- <tipDialog :msg="msg" :show.sync="showCon1"></tipDialog> -->
          <titleDialog
            @saveEndCharts="saveEndCharts"
            :show.sync="titleShow"
          ></titleDialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { chartEncaps } from '@/components/chartsType/chartEncaps/chartEncaps.js'
import chartsCondition from '@/components/chartsType/chartsCondition'
import chartsType from '@/components/chartsType'
import drawcharts from '@/components/chartsType/drawcharts'
import { createNamespacedHelpers } from 'vuex'
import confirmDialog from '@/components/chartsType/confirmDialog'
import tipDialog from '@/components/chartsType/tipDialog'
import titleDialog from '@/components/chartsType/titleDialog'
import sidebarWrap from '@/components/layout/sidebar/chartsSliderbar.vue'
import navWrap from '@/components/layout/nav/chartsNav.vue'
const { mapState, mapMutations, mapActions } = createNamespacedHelpers('charts')
const chartsConStore = createNamespacedHelpers('chartsCon')

export default {
  name: 'createCharts',
  data() {
    return {
      mychartsDom: {},
      // 右侧当前选中菜单
      activeName: '1',
      keywords: '', // 搜索关键词
      // 图表类型列表
      chartsType: ['全部', '饼状图', '柱状图', '折线图', '词云图', '地图'],
      dropData: '',
      chartsName: 'b1',
      showCon: false,
      titleShow: false,
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        '#FF0000',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)'
      ],
      userlist: {}
    }
  },
  methods: {
    // 清空绘制区域
    clearHtml() {
      this.mychartsDom.innerHTML = ''
    },
    // 下载数据
    downloadData() {
      if (this.mychartsDom.innerHTML !== '') {
        let arry = {
          '1-1': { ways: ['1', '5'], type: ['1', 'z1', 'z4'] },
          '1-2': { ways: ['1'], type: ['z2', 'z3'] },
          '2-1': { ways: ['2'], type: ['z1', 'z4', 'l2'] },
          '2-2': { ways: ['2', '5'], type: ['z2'] },
          '2-3': { ways: ['2', '5'], type: ['z3', 'l1'] },
          '4-1': { ways: ['3', '6'], type: ['5'] },
          '5-1': { ways: ['4'], type: ['4'] }
        }
        let statType
        let chartType
        let chartWays = this.chartsConData.ways
        let type = this.chartsConData.type
        let type1 = this.chartsConData.type1
        for (let i in arry) {
          if (
            arry[i].ways.includes(chartWays) &&
            (arry[i].type.includes(type) || arry[i].type.includes(type1))
          ) {
            let k = i.split('-')
            statType = k[0]
            chartType = k[1]
            break
          }
        }
        window.location.href = encodeURI(
          this.$axios.baseURL +
            'chart/downloadChartData?statType=' +
            statType +
            '&chartType=' +
            chartType +
            '&data=' +
            JSON.stringify(this.chartData)
        )
      } else {
        this.$confirm('提示', {
          title: '提示',
          message: '请选择图表和统计方式!',
          showCancelButton: false,
          confirmButtonText: '确定',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {})
      }
    },
    // 点击主题颜色拾色器
    handlePicker(val, i) {
      this.$nextTick(function() {
        this.setThemeColor({ key: i, value: val })
      })
    },
    // 设置主题色
    setTheme(val) {
      this.setChartsConData({ theme: val, themeColor: this.themeColor[val] })
    },
    // 图表搜索
    handleSearch(data) {
      this.setState([{ key: 'chartKeywords', value: data }])
      this.filterCharts()
    },
    // 点击图表类型
    handleChartsType(type) {
      this.setState([{ key: 'currentType', value: type }])
      this.filterCharts()
    },
    // 保存图表
    saveCharts() {
      if (this.mychartsDom.innerHTML !== '') {
        if (this.$route.params.id === 'new') {
          this.titleShow = true
        } else {
          this.saveEndCharts()
        }
      } else {
        this.$confirm('提示', {
          title: '提示',
          message: '请选择图表和统计方式！',
          // showCancelButton: true,
          confirmButtonText: '确定',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {})
      }
    },
    // 退出
    quit() {
      this.$router.push('/charts', () => {})
    },
    // 调用保存图标接口
    saveEndCharts(name) {
      name = name || this.chartsConData.name
      let doms = this.$refs.drawChart
      this.$html2canvas(doms.$refs.imageWrapper).then(canvas => {
        let dataURL = canvas.toDataURL('image/png')
        let imageBase64 = dataURL
        let file = this.dataURLtoFile(imageBase64, 'chartImg.jpg')
        // 通过formData传参
        let formData = new FormData()
        formData.append('file', file)
        formData.append('userId', Number(this.userlist.id))
        formData.append('chartName', name)
        formData.append('statType', Number(this.chartsConData.ways))
        formData.append('chartType', Number(this.chartsConData.type))
        formData.append('chartSonType', this.chartsConData.type1)
        formData.append('statSource', Number(this.formData.statSource))
        formData.append(
          'subclassfolderid',
          this.formData.statSourceId.join(',')
        )
        formData.append('chartStyle', JSON.stringify(this.chartsConData))
        formData.append('queryInfo', JSON.stringify(this.chartsCondition))
        formData.append('chartData', JSON.stringify(this.chartData))
        // 设置post请求的配置
        let config = {
          headers: {
            'content-type': 'multipart/form-data'
          }
        }
        // 新创建图表
        if (this.$route.params.id === 'new') {
          this.$axios.post('/chart/saveChart', formData, config).then(res => {
            if (res.status === 200) {
              if (res.data.message === '成功') {
                this.$router.push('/charts', () => {})
              }
            }
          })
        } else {
          // 编辑图表
          formData.append('chartId', this.$route.params.id)
          this.$axios.post('/chart/editChart', formData, config).then(res => {
            if (res.status === 200) {
              if (res.data.message === '操作成功') {
                this.$router.push('/charts', () => {})
              }
            }
          })
        }
      })
    },
    // 下载缩略图
    loadImg() {
      let doms = this.$refs.drawChart
      if (this.mychartsDom.innerHTML !== '') {
        this.$html2canvas(doms.$refs.imageWrapper).then(canvas => {
          let dataURL = canvas.toDataURL('image/png')
          var dlLink = document.createElement('a')
          dlLink.download = 'fileName'
          dlLink.href = dataURL
          dlLink.dataset.downloadurl = [
            'MIME_TYPE',
            dlLink.download,
            dlLink.href
          ].join(':')
          document.body.appendChild(dlLink)
          dlLink.click()
          document.body.removeChild(dlLink)
        })
      } else {
        this.$confirm('提示', {
          title: '提示',
          message: '请选择图表和统计方式！',
          // showCancelButton: true,
          confirmButtonText: '确定',
          type: 'warning'
        })
          .then(() => {})
          .catch(() => {})
      }
    },
    dataURLtoFile(dataurl, filename) {
      // 将base64转换为文件
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bstr = window.atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    rePaint() {
      this.$refs.drawChart.drawWhich(this.chartsConData.type1)
    },
    axiosData() {
      let newType = this.chartsConData.type // 新图形类型
      let oldWays = this.chartsConData.oldWays // 上一次的统计方式
      let newWays = this.chartsConData.ways // 新统计方式
      if (oldWays !== newWays) {
        this.setChartsConData({ oldType: newType })
        this.setChartsConData({ oldWays: newWays })
        this.dispatchNewData({
          vm: this,
          type: Number(this.chartsConData.type),
          axios: this.$axios
        }).then(res => {
          this.$refs.drawChart.drawWhich(this.chartsConData.type1)
        })
      } else {
        this.setChartsData({
          ways: this.chartsConData.ways,
          type1: this.chartsConData.type1,
          type: this.chartsConData.type,
          data: this.oldData
        })
        this.$refs.drawChart.drawWhich(this.chartsConData.type1)
      }
    },
    // 绘制图表
    renderData(data) {
      this.setshadeDisplay(false)
      this.mychartsDom.innerHTML = ''
      data = data || this.chartsConData.type1
      // 数据为零和没有选择图形不绘制
      if (!data) {
        return
      }
      // 如果当前统计方式支持绘制当前点击图表类型
      if (chartEncaps.ifDraw({ _t: this })) {
        this.setMergeNum()
        let oldType = this.chartsConData.oldType // 上一次的图形类型
        let newType = this.chartsConData.type // 新图形类型
        let oldWays = this.chartsConData.oldWays // 上一次的统计方式
        let newWays = this.chartsConData.ways // 新统计方式
        // 当统计方式为情感时，饼状图和柱状图两个切换需要重新请求接口数据
        switch (this.chartsConData.ways) {
          case '5':
            if (
              newWays === '5' &&
              oldWays === '5' &&
              ((oldType === '1' && newType === '2') ||
                (oldType === '1' && newType === '3') ||
                (oldType === '2' && newType === '1') ||
                (oldType === '3' && newType === '1'))
            ) {
              this.showCon = true
              return
            }
            this.setLoading(true)
            this.axiosData()
            break
          default:
            this.setLoading(true)
            this.axiosData()
        }
      } else {
        this.$confirm('提示', {
          title: '提示',
          message: '当前统计方式不支持此图标类型展示，请重新选择。',
          // showCancelButton: true,
          confirmButtonText: '确定',
          type: 'warning'
        })
          .then(() => {
            this.setLoading(false)
            this.setshadeDisplay(true)
          })
          .catch(() => {
            this.setLoading(false)
            this.setshadeDisplay(true)
          })
      }
    },
    // 更新数据，重新请求接口
    updateData() {
      let that = this
      let requestParams = this.$route.params
      if (requestParams.id && requestParams.id !== 'new') {
        this.$axios
          .get('/chart/queryChartDetail?chartId=' + requestParams.id)
          .then(res => {
            let result = res.data.result
            if (res.status === 200) {
              if (res.data.message === '成功') {
                that.setFormData({ data: JSON.parse(result.queryinfo) })
                that.getConditionData({ data: JSON.parse(result.queryinfo) })
                that.setChartsConData(JSON.parse(result.chartstyle))
                that.resetThemeColor()
                that.setChartsData1({
                  data: JSON.parse(result.chartdata)
                })
                that.$refs.drawChart.drawWhich(that.chartsConData.type1)
              }
            }
          })
      }
    },

    ...mapMutations([
      'setChartsData',
      'setChartsData1',
      'setChartsConData',
      'setFormData',
      'getConditionData',
      'setshadeDisplay',
      'setTime',
      'setThemeColor',
      'resetThemeColor',
      'setLoading',
      'setStoreParams',
      'setMergeNum'
    ]),
    ...chartsConStore.mapMutations(['setState']),
    ...mapActions(['dispatchNewData']),
    ...chartsConStore.mapActions(['filterCharts'])
  },
  mounted() {
    if (JSON.parse(localStorage.getItem('userlist'))) {
      this.userlist = JSON.parse(localStorage.getItem('userlist'))
    }
    let obj = [
      { key: 'formData', value: this.oldFormData },
      { key: 'chartsCondition', value: this.oldFormData },
      { key: 'chartsConData', value: this.oldchartsConData }
    ]
    this.setStoreParams(obj)
    let draw = this.$refs.drawChart
    this.mychartsDom = draw.$refs.mycharts
    this.setTime({
      key: 'startTime',
      value: this.chartsCondition.issuedataStart
    })
    this.setTime({
      key: 'endTime',
      value: this.chartsCondition.issuedataEnd
    })
    this.updateData()
  },
  computed: {
    ...mapState([
      'chartsCondition',
      'chartData',
      'chartsConData',
      'oldData',
      'formData',
      'startTime',
      'endTime',
      'themeColor',
      'oldFormData',
      'oldchartsConData',
      'shadeDisplay'
    ]),
    ...chartsConStore.mapState(['chartKeywords', 'currentType'])
  },
  watch: {},
  components: {
    chartsType,
    chartsCondition,
    drawcharts,
    confirmDialog,
    tipDialog,
    titleDialog,
    sidebarWrap,
    navWrap
  }
}
</script>

<style scoped>
.home {
  width: 100%;
  height: 100vh;
  overflow-x: auto;
}
.content {
  min-width: 1200px;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  height: 100vh;
  display: flex;
}
.conArea {
  width: calc(100vw - 50px);
  min-width: 1150px;
  position: relative;
}
.loading {
  position: absolute;
  height: 20%;
  bottom: 40%;
  width: 100%;
  display: block;
  text-align: center;
}
.create-charts {
  background-color: #f0f2f5;
  box-sizing: border-box;
  width: 100%;
  position: absolute;
  top: 60px;
  bottom: 0;
  overflow: auto;
}

.create-charts .control-btn {
  margin-top: 10px;
  margin-left: 10px;
}
.canvasdraw {
  min-height: 865px;
  position: absolute;
  top: 0;
  bottom: 0;
}
.create-charts .control-pane {
  background-color: #304156;
  box-sizing: border-box;
  height: calc(100vh - 60px);
  height: -moz-calc(100vh - 60px);
  height: -webkit-calc(100vh - 60px);
  overflow: auto;
}
.create-charts .control-pane .edit-btn {
  text-align: right;
  margin: 10px 0;
}
.create-charts .save-btn {
  background-color: #f0f3f4;
  text-align: center;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 15px;
  width: 100%;
}
.create-charts .save-btn > button {
  display: inline-flex;
  align-items: center;
}
.create-charts .control-pane .show-pane {
  border: 1px solid #eee;
  background-color: #fff;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border: 1px solid #ddd;
  height: calc(100% - 38px);
  height: -moz-calc(100% - 38px);
  height: -webkit-calc(100% - 38px);
  padding-top: 20px;
  padding-bottom: 20px;
}
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.charts-select-con {
  margin-top: 15px;
  position: relative;
  height: 100%;
}
.router-link-active {
  color: #409eff;
}
.themeStyle {
  color: #eee;
}
.default-theme,
.define-theme1 {
  background-color: #fff;
  padding: 7px 5px;
  margin: 10px auto 0;
  margin-top: 10px;
  height: 20px;
  color: #eee;
  display: block;
  cursor: pointer;
  border: 2px solid #fff;
}
.theme-active {
  border: 2px solid #c33409;
}
.themeDiv {
  display: inline-block;
  margin-left: 22px;
}
.default-theme span,
.define-theme1 span {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin: 0 4px;
}
.el-menu-item.is-active {
  color: #4aa5f9 !important;
}
</style>
